package com.monlyu.bo;

import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.monlyu.bean.Page;
import com.monlyu.bean.Pages;
import com.monlyu.util.DateUtil;
import com.monlyu.util.LogUtil;
import com.monlyu.util.StringUtil;
import com.monlyu.util.WebOptUtil;
import com.monlyu.vo.Notice;

/*        
 * @creator   曾俊 
 * @create-time 2010-2-6 下午10:46:15    
 */
@Repository(value = "noticeBo")
public class NoticeBo extends BaseBo {

	public void insert(Notice notice) {
		checkNotice(notice);
		notice.setCreateUser(WebOptUtil.curUser());
		dao.insertOrUpdate(notice);
	}

	private void checkNotice(Notice notice) {
		if (notice.getTitle() == null) {
			LogUtil.log(getClass()).warn("公告标题不能为空！");
		}
		if (notice.getContent() == null) {
			LogUtil.log(getClass()).warn("公告内容不能为空！");
		}
		if (notice.getCreateDate() == null) {
			LogUtil.log(getClass()).warn("公告发布时间不能为空！");
		}
		if (notice.getDeadDate() == null) {
			LogUtil.log(getClass()).warn("公告结束时间不能为空！");
		}
	}

	public void update(Notice notice) {
		checkNotice(notice);
		Notice dbNotice = dao.get(Notice.class, notice.getId());
		dbNotice.setContent(notice.getContent());
		dbNotice.setTitle(notice.getTitle());
		dbNotice.setCreateDate(notice.getCreateDate());
		dbNotice.setDeadDate(notice.getDeadDate());
		dao.update(dbNotice);
	}

	public void load(Notice notice) {
		dao.load(notice);
	}

	public void delete(Notice notice) {
		dao.delete(Notice.class, notice.getId());
	}

	public Pages<Notice> search(Page page) {
		Criteria criteria = dao.initCriteria(Notice.class);
		if (!StringUtil.isEmpty(page.getKey())) {
			criteria.add(Restrictions.like("title", page.getKey().trim(),
					MatchMode.ANYWHERE));
		}
		criteria.add(Restrictions.ge("deadDate", DateUtil.now()));
		criteria.addOrder(Order.desc("createDate"));
		return findByCriteria(page.getNo(), page.getSize(), criteria);
	}
}
